<template>
    <div class="container">
        <el-input v-model="input" style="width: 240px;margin-left: 2rem" placeholder="请输入塔型名称" />
        <el-button style="width: 6rem;margin-left: 2rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="filterUser">查询</el-button>
        <el-button style="width: 6rem;background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" type="primary" @click="newUser"  v-if="hasPermission(authStore.permissions,21)">新建塔型</el-button>
        <!-- 点击新建角色打开 -->
        <el-dialog v-model="visible" :show-close="false" width="800">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <div>新建/修改塔型</div>
          <el-button type="danger" @click="close">
            <el-icon class="el-icon"><CircleCloseFilled /></el-icon>
          </el-button>
        </div>
      </template>

      <!-- 输入框区域 -->
      <div style="display: flex;"></div>

      <div style="display: flex; margin-top: 1rem; flex-direction: column;">
  <div style="display: flex;">
    <div class="input-text">
      <span style="color: red;">*</span>塔型名称:
    </div>
    <el-input style="width: 240px" v-model="towerTypeName" @input="towerTypeErrors.typeName = false" />
  </div>
  <p v-if="towerTypeErrors.typeName" class="error-text">请输入塔型名称</p>
</div>

        
        <div style="display: flex;margin-top: 1rem">
        <div class="input-text">
        <span style="color: transparent;">*</span>
          备注：
        </div>
        <el-input style="width: 240px" v-model="userMessage"></el-input>
        </div>
      <!-- 保存和取消按钮 -->
      <div style="margin-top: 2rem;position: relative;height: 3rem;">
        <div style="position: absolute;right: 0;">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="sumbitMessage()">保存</el-button>
        </div>
      </div>
        </el-dialog>

        <!-- 点击配置打开 -->
        <el-dialog v-model="visible1" :show-close="false" width="800">
      <template #header="{ close}">
        <div class="my-header">
          <div>部位信息维护</div>
          <el-button type="danger" @click="close">
            <el-icon class="el-icon"><CircleCloseFilled /></el-icon>
          </el-button>
        </div>
      </template>
      <hr>
      <div class="my-header">
          <div><span style="color: blue;">{{setTowerTypeName}}</span> - <span>部位信息维护</span></div>
          <el-button type="success" @click="addTowerPosition">添加部位</el-button>
        </div>

      <!-- 展示表格区域-->

<el-table :data="getTowerPositionByName" style="width: 100%; margin-top: 3rem;">
  <el-table-column label="序号" width="100">
  <template #default="{ row, $index }">
      <span>{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
  </template>
</el-table-column>

  <el-table-column prop="role.roleName" label="部位名称" width="150">
  <template #default="{ row }">
      <span  style="color: black;">{{ row.positionName}}</span>
  </template>
</el-table-column>

  <el-table-column prop="role.roleName" label="照片编号" width="150">
  <template #default="{ row }">
      <span  style="color: black;">{{ row.pictureNumber}}</span>
  </template>
</el-table-column>

  <el-table-column prop="role.roleName" label="部位类型" width="150">
  <template #default="{ row }">
      <span  style="color: gray;">{{ row.positionType}}</span>
  </template>
</el-table-column>

<el-table-column fixed="right" label="操作" min-width="200">
  <template #default="{ row }">
      <div>
        <el-button link type="primary" size="small" @click="changeTowerRole(row)" >编辑</el-button>
        <el-button link type="primary" size="small" @click="deletePosition(row)" >删除</el-button>
    </div>
  </template>
</el-table-column>
</el-table>
      <!-- 保存和取消按钮 -->
      <div style="margin-top: 2rem;position: relative;height: 3rem;">
        <div style="position: absolute;right: 0;">
          <el-button @click="visible1 = false">关闭</el-button>
        </div>
      </div>
        </el-dialog>



        <!-- 点击添加或者修改部位的时候出现的弹窗 -->
        <el-dialog v-model="visible2" :show-close="false" width="500">
      <template #header="{ close}">
        <div class="my-header">
          <div>新建/修改部位</div>
          <el-button type="danger" @click="close">
            <el-icon class="el-icon"><CircleCloseFilled /></el-icon>
          </el-button>
        </div>
      </template>
      <!-- 输入框区域 -->
<!-- 部位类型 -->
<div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text">
      <span style="color: red;">*</span>部位类型:
    </div>
    <el-radio-group v-model="radio1" @change="towerPositionErrors.positionType = false">
      <el-radio value="平台部位" size="large">平台部位</el-radio>
      <el-radio value="多面塔身部位" size="large">多面塔身部位</el-radio>
      <el-radio value="其他部位" size="large">其他部位</el-radio>
    </el-radio-group>
  </div>
  <p v-if="towerPositionErrors.positionType" class="error-text">请选择部位类型</p>
</div>

<!-- 部位名称 -->
<div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text">
      <span style="color: red;">*</span>部位名称:
    </div>
    <el-input style="width: 240px" v-model="towerPositionName" @input="towerPositionErrors.positionName = false" />
  </div>
  <p v-if="towerPositionErrors.positionName" class="error-text">请输入部位名称</p>
</div>

<!-- 照片编号数 -->
<div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text">
      <span style="color: red;">*</span>照片编号数:
    </div>
    <el-select v-model="imageNumber" placeholder="照片编号数量" style="width: 240px" @change="towerPositionErrors.pictureNumber = false">
      <el-option v-for="item in imagesCount" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
  </div>
  <p v-if="towerPositionErrors.pictureNumber" class="error-text">请选择照片编号数</p>
</div>

<!-- 起始编号 -->
<div style="display: flex; flex-direction: column; margin-top: 1rem;">
  <div style="display: flex;">
    <div class="input-text">
      <span style="color: red;">*</span>起始编号：
    </div>
    <el-input style="width: 240px" v-model="startNumber" @input="towerPositionErrors.startNumber = false" />
  </div>
  <p v-if="towerPositionErrors.startNumber" class="error-text">请输入起始编号</p>
</div>


        <!-- 绑定的算法 -->
        <div style="display: flex;margin-top: 1rem">
        <div class="input-text">
          绑定算法：
        </div>
        <el-select
          v-model="valueAlgorithm"
          multiple
          placeholder="算法选择（可多选）"
          style="width: 240px"
        >
          <el-option
            v-for="item in AlogrithmOptions" 
            :key="item?.value"
            :label="item.label"
            :value="item.value"
          />
    </el-select>
        </div>

      <!-- 保存和取消按钮 -->
      <div style="margin-top: 2rem;position: relative;height: 3rem;">
        <div style="position: absolute;right: 0;">
          <el-button @click="visible2 = false">取消</el-button>
          <el-button type="primary" @click="sumbitAddPosition()">保存</el-button>
        </div>
      </div>
        </el-dialog>


        <el-table :data="displayedData" style="width: 99%; margin-top: 3rem;">
      <el-table-column label="序号" width="100">
        <template #default="{ row, $index }">
      <span>{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
        </template>
      </el-table-column>

  <el-table-column prop="role.roleName" label="塔型名称" width="150">
        <template #default="{ row }">
      <span  style="color: black;">{{ row.towerType.typeName }}</span>
        </template>
      </el-table-column>
      
  <el-table-column prop="role.roleName" label="部位数" width="150">
        <template #default="{ row }">
       <el-button link type="primary" size="small" v-if="row.towerPositions.length === 0  && hasPermission(authStore.permissions,22)" @click="changeTowerPosition(row)" >配置</el-button>
      <span v-else-if="hasPermission(authStore.permissions,22)"  style="color: skyblue;cursor:pointer" @click="changeTowerPosition(row)">{{ row.towerPositions.length}}</span>
      <span v-else style="color: skyblue;cursor:pointer">{{ row.towerPositions.length}}</span>


        </template>
      </el-table-column>

  <el-table-column prop="role.roleName" label="描述" width="150">
    <template #default="{ row }">
      <span  style="color: gray;">{{ row.towerType.description }}</span>
    </template>
  </el-table-column>
  
  <el-table-column prop="role.createTime" label="创建时间" width="200">
    <template #default="{ row }">
      <span  style="color: gray;">{{ row.towerType.createTime }}</span>

    </template>
  </el-table-column>
  <el-table-column prop="role" label="关联算法" width="270">
    <template #default="{ row }">
      <span  style="color: gray;">{{  row?.towerPositions && row?.towerPositions.length
          ? [...new Set(
              row?.towerPositions
                .flatMap((pos:any) => (pos?.algorithmList || []).map((algo:any) => algo?.algorithmName))
            )].join('，')
          : ''
      }}</span>

    </template>
  </el-table-column>
  
  <el-table-column fixed="right" label="操作" min-width="100">
    <template #default="{ row }">
      <div>
        <el-button link type="primary" size="small" @click="changeRole(row)"  v-if="hasPermission(authStore.permissions,23)" style="color: rgb(110, 78, 208);">编辑</el-button>
        <el-button link type="primary" size="small" @click="deleteTower(row)"  v-if="hasPermission(authStore.permissions,24)" style="color:#f56c6c;">删除</el-button>
      </div>
    </template>
  </el-table-column>
</el-table>
<!-- 这里写分页页面 -->

<el-pagination
  style="margin-top:2rem;"
  v-model:current-page="currentPage"
  v-model:page-size="pageSize"
  :total="total"
  layout="prev, pager, next, jumper"
  :background="true"
  @current-change="handleCurrentChange"
/>

    </div>


    <el-dialog v-model="deleteVisible" title="提示" width="500" center>
            <span>
              是否需要删除通信塔 "{{deleteItem.towerType?.typeName}}"
            </span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteVisible = false">取消</el-button>
              <el-button type="primary" @click="handleClick()">
               确认删除
            </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="deleteVisible1" title="提示" width="500" center>
            <span>
              是否需要删除部位: "{{deletePositionItem.positionName}}"
            </span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteVisible1 = false">取消</el-button>
              <el-button type="primary" @click="handleClick1()">
               确认删除
            </el-button>
          </div>
        </template>
      </el-dialog>

</template>

<script lang="ts" setup>
    import { hasPermission } from '@/utils/permissionUtils';
    import { ElMessage } from 'element-plus'
    import { CircleCloseFilled } from '@element-plus/icons-vue';
    import { ref ,onMounted ,nextTick } from 'vue'
    import request from '@/utils/request';
    import { useAuthStore } from '@/stores/user';
    import showMessage from '@/utils/showMessage';
    const authStore = useAuthStore();//使用store仓库进行数据管理
    const deleteVisible1 = ref()
    const tableData = ref([]); // 原始数据
    const displayedData = ref([]); // 当前页显示的数据
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页条数
    const total = ref(0); // 总条数
    const input = ref('')
    const towerTypeName = ref('')
    const userMessage = ref('')
    const visible = ref(false)//新建塔形组件
    const visible1 = ref(false)//配置部位组件
    const visible2 = ref(false)//新建/修改部位
    const radio1 = ref("其他部位")//修改部位的单选框
    const updataTowerId = ref()
    const currentTab = ref(1)
    const flag = ref()//flag为1代表是新建，为2表示是修改
    const flag1 = ref()//flag为1代表是新建，为2表示是修改

    const imageNumber = ref()
    const towerPositionName = ref()//铁塔位置名称
    const startNumber = ref() //起始编号

    const valueAlgorithm = ref([]) //算法选择绑定,多选，所以是数组


    

    const AlogrithmOptions = ref<any>()


const imagesCount = [
  {
    value: 1,
    label: '1',
  },
  {
    value: 2,
    label: '2',
  },
  {
    value: 3,
    label: '3',
  },
  {
    value: 4,
    label: '4',
  },
  {
    value: 5,
    label: '5',
  },
  {
    value: 6,
    label: '6',
  },
]
    // 新建角色
    const newUser= () => {
      towerTypeName.value = '',
        userMessage.value = '',
      visible.value = true;
      flag.value = 1
    }

    const filterUser = () => {
      const  towerTypeName = input.value || ''
      if  (towerTypeName == '') {
        displayedData.value
      }else {        
       const filteredData  = displayedData.value.filter((item:any) =>{
         return item.towerType.typeName === towerTypeName
        })

        displayedData.value = filteredData
      }
    }
    
    // 删除逻辑
    const deleteVisible = ref(false)
    const deleteItem = ref()
    const deleteTower = (row:any) => {
      deleteVisible.value = true
      deleteItem.value = row
    }

      deleteVisible1.value = false
      const deletePositionItem = ref()
    const deletePosition = (row:any) => {
      deleteVisible1.value = true
      deletePositionItem.value = row
    }


    // 校验对象
    const towerTypeErrors = ref({
      typeName: false,
    });

    const towerPositionErrors = ref({
      positionType: false,
      positionName: false,
      pictureNumber: false,
      startNumber: false,
    });
    // 新建/修改塔型提交校验
const validateTowerType = () => {
  let isValid = true;
  if (!towerTypeName.value.trim()) {
    towerTypeErrors.value.typeName = true;
    isValid = false;
  } else {
    towerTypeErrors.value.typeName = false;
  }
  return isValid;
};

const validateTowerPosition = () => {
  let isValid = true;
  if (!radio1.value) {
    towerPositionErrors.value.positionType = true;
    isValid = false;
  } else {
    towerPositionErrors.value.positionType = false;
  }

  if (!towerPositionName.value.trim()) {
    towerPositionErrors.value.positionName = true;
    isValid = false;
  } else {
    towerPositionErrors.value.positionName = false;
  }

  if (!imageNumber.value) {
    towerPositionErrors.value.pictureNumber = true;
    isValid = false;
  } else {
    towerPositionErrors.value.pictureNumber = false;
  }

  if (!startNumber.value) {
    towerPositionErrors.value.startNumber = true;
    isValid = false;
  } else {
    towerPositionErrors.value.startNumber = false;
  }

  return isValid;
};

    const handleClick =() => {
        request.post("/resource/deleteTowerType",{
          id:deleteItem.value.towerType.id,
        }).then(
          (res)=>{
            showMessage(res)
            if(res.status == 200){
            //删除用户日志 
              request.post('/user/insertOperation',{
                username : authStore.user?.username,
                name : authStore.user?.name,
                organizationID:authStore.organizationID,
                ip:null,
                operationModel:"资源管理",
                operationResult:"删除通信塔类别成功",
                operationTime:null,
                operationType:"operation"
              }).then(res => {
              
              })
              // 获取所有信息
              getAllTowerType()
              deleteVisible.value = false
            }
          }
        )
    }
      // 删除逻辑
      const handleClick1 =() => {        
        request.post("/resource/deletePositionByID",{
          id:deletePositionItem.value.id,
        }).then(
          (res)=>{
            showMessage(res)
            if(res.status == 200){
              // 获取所有信息
              getTowerPosition(changeTowerName.value)
              getAllTowerType()
              deleteVisible1.value = false
            }
          }
        )
    }

//添加杆塔部位
const addTowerPosition = () => {
  visible2.value = true;
  flag1.value = 1;
  radio1.value = '其他部位'
  towerPositionName.value = ''
  imageNumber.value =  ''
  startNumber.value = ''
}
const updataPositionId = ref()
const changeTowerItem = ref()
const changePosition = ref()
const changeTowerRole = (row:any) => {

  towerTypeErrors.value = {
      typeName: false,
    };

  towerPositionErrors.value = {
      positionType: false,
      positionName: false,
      pictureNumber: false,
      startNumber: false,
    };

  valueAlgorithm.value = row.algorithmList.map((item:any) => item?.id);
  changePosition.value = row
  visible2.value = true;
  flag1.value = 2;
  updataPositionId.value = row.id
  radio1.value = row.positionType
  towerPositionName.value = row.positionName
  imageNumber.value = row.pictureNumber.split('-').length;
  startNumber.value = row.pictureNumber.split('-')[0]  
}

    // 修改逻辑
    const changeRole = (row: any) => {
      towerTypeErrors.value = {
      typeName: false,
    };

  towerPositionErrors.value = {
      positionType: false,
      positionName: false,
      pictureNumber: false,
      startNumber: false,
    };

        changeTowerItem.value  = row
  
        userMessage.value = row.towerType.description;//备注
        towerTypeName.value = row.towerType.typeName
        updataTowerId.value = row.towerType.id
        // 提取权限数据
        visible.value = true;
        flag.value = 2;
};
//配置部位信息
const changeTowerId = ref()
const changeTowerName = ref()
const selectedTowerPosition = ref()
const getTowerPositionByName = ref()
const setTowerTypeName  = ref()
const changeTowerPosition = (row:any) => {
  setTowerTypeName.value = row.towerType.typeName
  
  getTowerPosition(row.towerType.typeName)
  getAllTowerType()
  changeTowerId.value = row.towerType.id
  changeTowerName.value = row.towerType.typeName
  visible1.value = true
  
}

const getTowerPosition  = (id:any) => {

  const formatDate = new FormData()
  formatDate.append('towerTypeName',id)  
  request.post('/resource/getTowerTypeByTypeName',formatDate).then((res:any)=>{

    getTowerPositionByName.value = res.data.towerPositions    
  })
}
//新增
const sumbitMessage = () => {
  if (!validateTowerType()) return;
  if (flag.value === 1) {
    const typeName = towerTypeName.value;
    const description = userMessage.value;
    request.post('/resource/insertTowerType', { typeName, description }).then((res) => {
      showMessage(res);
      if (res.status === 200) {
        visible.value = false;
        towerTypeName.value = '';
        userMessage.value = '';
        request.post('/user/insertOperation', {
          username: authStore.user?.username,
          name: authStore.user?.name,
          organizationID: authStore.organizationID,
          ip: null,
          operationModel: '资源管理',
          operationResult: '新建塔型成功',
          operationTime: null,
          operationType: 'operation',
        });
        getAllTowerType();
      }
    });
  } else if (flag.value === 2) {
    const typeName = towerTypeName.value;
    const description = userMessage.value;
    const id = updataTowerId.value;
    const primaryTypeName = changeTowerItem.value.towerType.typeName;
    request.post('/resource/updateTowerType', {
      id,
      typeName,
      description,
      primaryTypeName,
    }).then((res) => {
      showMessage(res);
      if (res.status === 200) {
        visible.value = false;
        towerTypeName.value = '';
        userMessage.value = '';
        request.post('/user/insertOperation', {
          username: authStore.user?.username,
          name: authStore.user?.name,
          organizationID: authStore.organizationID,
          ip: null,
          operationModel: '资源管理',
          operationResult: '修改塔型',
          operationTime: null,
          operationType: 'operation',
        });
        getAllTowerType();
      }
    });
  }
};

const sumbitAddPosition = () => {
  if (!validateTowerPosition()) return;
  const newPictureNumber = [];
  const imageCount = Number(imageNumber.value);
  const start = Number(startNumber.value);
  for (let i = 0; i < imageCount; i++) {
    newPictureNumber.push(start + i);
  }
  const result = newPictureNumber.join('-');
  const payload = {
    positionName: towerPositionName.value,
    positionType: radio1.value,
    pictureNumber: result,
    towerTypeID: changeTowerId.value,
    algorithmIDs: valueAlgorithm.value,
  };
  if (flag1.value === 1) {
    request.post('/resource/configurePosition', payload).then((res) => {
      showMessage(res);
      if (res.status === 200) {
        valueAlgorithm.value = [];
        getTowerPosition(changeTowerName.value);
        getAllTowerType()
        visible2.value = false;
      }
    });
  } else if (flag1.value === 2) {
    request.post('/resource/updatePosition', {
      ...payload,
      id: updataPositionId.value,
      primaryPositionName: changePosition.value.positionName,
    }).then((res) => {
      showMessage(res);
      if (res.status === 200) {
        valueAlgorithm.value = [];
        getTowerPosition(changeTowerName.value);
        getAllTowerType()
        visible2.value = false;
      }
    });
  }
};


//获取所有的杆塔类型
const getAllTowerType = () => {
  request.get('/resource/getAllTowerType').then((res)=> {
    displayedData.value = res.data 

       
  })
}

// 获取所有的算法
const getAllAlgorithm = () => {
  request.get("resource/getAllAlgorithm").then((res: any) => {
    const rawData = res.data;

    // 去重 typeName 并转为 options 格式
    const typeNameSet = new Set<string>();
    AlogrithmOptions.value = rawData
      .filter((item: any) => {
        if (!typeNameSet.has(item.algorithm.algorithmName)) {
          typeNameSet.add(item.algorithm.algorithmName);
          return true;
        }
        return false;
      })
      .map((item: any) => ({
        value: item.algorithm.id,
        label: item.algorithm.algorithmName
      }));  
  });
};


// 更新显示的数据
const updateDisplayedData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  const currentData = tableData.value.slice(start, end);

  // 填充空行以确保表格显示10行
  displayedData.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});  
};

// 处理分页切换
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  updateDisplayedData();
};

  onMounted(()=>{
   getAllTowerType()
   getAllAlgorithm()
  })

</script>

<style scoped>
.container {
    width: 100%;
    height: calc(100vh - 100px);
    display: block;
    padding: 20px;
    box-sizing: border-box;
}
.container-head {
    display: flex
} 
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
.input-text {
    width: 20%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.input-text1 {
    width: 10%;
    height: 2rem;
    line-height: 2rem;
    margin-left: 1rem;
}
.selected-tab {
  background-color: #409eff;
  color: white;
}
.empty-row {
  background-color: #f5f7fa;
  color: gray;
  text-align: center;
}
.error-text {
  color: red;
  font-size: 12px;
  margin-left: 6rem;
  margin-top: 0.25rem;
}

</style>